<template>
  <div class="app-container exam-paper-container">
    <!-- 左边：题库列表 -->
    <div class="left-panel" v-if="workArea">
      <h3>题库</h3>
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showLeftSearch" label-width="68px">
         <el-form-item label="试题编号" prop="questionId">
        <el-input
          v-model="queryParams.questionId"
          placeholder="请输入试题编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程" >
        <el-input
          v-model="queryParams.course"
          placeholder="请输入查询的课程"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="试题类型" >
          <el-select style="width: 200px;" v-model="queryParams.questionType" placeholder="请选择试题类型">
            <el-option
              v-for="dict in exam_question_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="试题难度" prop="level">
         <el-select style="width: 200px;" v-model="queryParams.level" placeholder="请选择试题难度">
            <el-option
              v-for="dict in exam_question_level"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="课程章节" prop="section">
        <el-input
          v-model="queryParams.section"
          placeholder="请输入课程章节"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="addToPaper"
        >添加到试卷</el-button>
      </el-col>
            <right-toolbar v-model:showSearch="showLeftSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table :data="questionList"  style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" align="center" width="50"></el-table-column>
        <el-table-column prop="questionId" align="center" label="试题编号" width="80"></el-table-column>
        <el-table-column prop="course" align="center" label="课程名称" width="120"></el-table-column>
        <el-table-column prop="question" align="center" label="题目内容">
          <template #default="scope">
          {{ scope.row.question.length > 5 ? scope.row.question.slice(0, 5) + '...' : scope.row.question }}
          </template>
        </el-table-column>
        <el-table-column prop="questionType" align="center" label="类型" width="100">
          <template #default="scope">
    {{ proxy.selectDictLabel(exam_question_type, scope.row.questionType) }}
  </template>
        </el-table-column>
        <el-table-column prop="score" align="center" label="分数" width="80"></el-table-column>
        <el-table-column label="操作" align="center" width="120">
          <template #default="scope">
            <el-button link @click="addToPaper(scope.row)">添加到试卷</el-button>
            <el-button link @click="handleDetial(1,scope.row)"  >查看试题</el-button>
          </template>
        </el-table-column>
      </el-table>

          <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

      <!-- 点击查看试卷详细 -->
    <el-dialog :title="title" v-model="questionOpen" width="500px" append-to-body>
      <el-form ref="questionRef" :model="form"  label-width="80px">
        <el-form-item label="课程名称" >
          <el-input  :value="form.course" readonly  />
        </el-form-item>
          <el-form-item label="试题类型" >
          <el-input  :value="proxy.selectDictLabel(exam_question_type, form.questionType)" readonly   >
          </el-input>
        </el-form-item>
        <el-form-item label="试题内容" >
          <el-input :value="form.question" readonly />
        </el-form-item>
        <el-form-item v-if="form?.questionType == 2" label="A选项" >
          <el-input  :value="form.aOption" readonly  /> 
        </el-form-item>
        <el-form-item v-if="form?.questionType == 2" label="B选项" >
          <el-input  :value="form.bOption" readonly  />  
        </el-form-item>
        <el-form-item v-if="form?.questionType == 2" label="C选项" >
          <el-input  :value="form.cOption" readonly  />   
        </el-form-item>
        <el-form-item v-if="form?.questionType == 2" label="D选项" >
          <el-input  :value="form.dOption" readonly  />   
        </el-form-item>
        <el-form-item label="正确答案" >
          <el-input  :value="form.answer" readonly  />
        </el-form-item>
        <el-form-item label="题目解析" >
          <el-input  :value="form.analysis" readonly  />
        </el-form-item>
        <el-form-item label="分数" >
          <el-input  :value="form.score" readonly  />
        </el-form-item>
        <el-form-item label="难度等级" >
          <el-input  :value="proxy.selectDictLabel(exam_question_level, form.level)" readonly   />
        </el-form-item>
        <el-form-item label="课程章节" >
          <el-input  :value="form.section" readonly  />
        </el-form-item>
      </el-form>
    </el-dialog>
    </div>

    <!-- 右边：试卷编辑区 -->
    <div class="right-panel" v-if="paperArea">
    <el-button @click="changeworkArea">{{workArea==false?"打开题库列表":"隐藏题库列表"}}</el-button>
  <el-row :gutter="10" style="margin-bottom: 20px;" v-if="paperInfoArea">
  <el-col :span="8">
    <div class="info-card">
      <span class="label">试卷编号：</span>
      <span class="value">{{ exam.examCode || '--' }}</span>
    </div>
  </el-col>

  <el-col :span="8">
    <div class="info-card">
      <span class="label">试卷名称：</span>
      <span class="value">{{ exam.source+exam.description || '未命名试卷' }}</span>
    </div>
  </el-col>

  <el-col :span="8">
    <div class="info-card">
      <span class="label">总题数：</span>
      <span class="value">{{ exam.paperDetail[0]+exam.paperDetail[1]+exam.paperDetail[2] }}</span>
    </div>
  </el-col>

  <el-col :span="8">
    <div class="info-card">
      <span class="label">判断题：</span>
      <span class="value">{{ exam.paperDetail[0] || 0 }}</span>
    </div>
  </el-col>

  <el-col :span="8">
    <div class="info-card">
      <span class="label">选择题：</span>
      <span class="value">{{ exam.paperDetail[1] || 0 }}</span>
    </div>
  </el-col>

  <el-col :span="8">
    <div class="info-card">
      <span class="label">填空题：</span>
      <span class="value">{{ exam.paperDetail[2] || 0 }}</span>
    </div>
  </el-col>
    <el-col :span="8">
    <div class="info-card">
      <span class="label">试卷总分：</span>
      <span class="value">{{ exam.totalScore }}</span>
    </div>
  </el-col>
      </el-row>

        <el-form :model="paperQueryParams" ref="queryRef" :inline="true" v-show="showRightSearch" label-width="68px">
         <el-form-item label="试题编号" prop="questionId">
        <el-input
          v-model="paperQueryParams.questionId"
          placeholder="请输入试题编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程" >
        <el-input
          v-model="paperQueryParams.course"
          placeholder="请输入查询的课程"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="试题类型" >
          <el-select style="width: 200px;" v-model="paperQueryParams.questionType" placeholder="请选择试题类型">
            <el-option
              v-for="dict in exam_question_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="试题难度" prop="level">
         <el-select style="width: 200px;" v-model="paperQueryParams.level" placeholder="请选择试题难度">
            <el-option
              v-for="dict in exam_question_level"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="课程章节" prop="section">
        <el-input
          v-model="paperQueryParams.section"
          placeholder="请输入课程章节"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handlePaperQuery" >搜索</el-button>
          <el-button icon="Refresh" @click="resetPaperQuery">重置</el-button>
          <el-button icon="Refresh" @click="maskPaperInfo">{{ paperInfoArea==true?'隐藏试卷信息':'显示试卷信息' }}</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          @click="handleDelete"
        >删除试题</el-button>
      </el-col>
            <right-toolbar v-model:showSearch="showRightSearch" @queryTable="getPaperList()"></right-toolbar>
      </el-row>

      <el-table  :data="paperList"   @selection-change="paperHandleSelectionChange">
        <el-table-column width="55" align="center" type="selection" ></el-table-column>
        <el-table-column min-width="5" align="center" type="index" label="序号"  ></el-table-column>
        <el-table-column  prop="question"  label="题目内容" ></el-table-column>
        <el-table-column width="100" align="center"  prop="questionType" label="类型" >
      <template #default="scope">
       {{ proxy.selectDictLabel(exam_question_type, scope.row.questionType) }}
     </template>
        </el-table-column>
        <el-table-column  prop="answer" align="center" label="答案" width="80" ></el-table-column>
        <el-table-column  prop="score" align="center" label="分数" width="80" ></el-table-column>
        <el-table-column  label="操作"  min-width="20">
          <template #default="scope">
            <el-button link type="Delete" @click="handleDelete(scope.row)">移除</el-button>
            <el-button link @click="handleDetial(2,scope.row)"  >查看试题</el-button>          </template>
        </el-table-column>
      </el-table>
      <pagination
      v-show="total>0"
      :total="paperTotal"
      v-model:page="paperQueryParams.pageNum"
      v-model:limit="paperQueryParams.pageSize"
      @pagination="getPaperList"
    />
     <el-dialog  :title="title" v-model="paperQuestionOpen" width="500px" append-to-body>
      <el-form ref="questionRef" :model="form"  label-width="80px">
        <el-form-item label="课程名称" >
          <el-input  :value="form.course" readonly  />
        </el-form-item>
          <el-form-item label="试题类型" >
          <el-input  :value="proxy.selectDictLabel(exam_question_type, form.questionType)" readonly   >
          </el-input>
        </el-form-item>
        <el-form-item label="试题内容" >
          <el-input :value="form.question" readonly />
        </el-form-item>
        <el-form-item v-if="form?.questionType == 2" label="A选项" >
          <el-input  :value="form.aOption" readonly  /> 
        </el-form-item>
        <el-form-item v-if="form?.questionType == 2" label="B选项" >
          <el-input  :value="form.bOption" readonly  />  
        </el-form-item>
        <el-form-item v-if="form?.questionType == 2" label="C选项" >
          <el-input  :value="form.cOption" readonly  />   
        </el-form-item>
        <el-form-item v-if="form?.questionType == 2" label="D选项" >
          <el-input  :value="form.dOption" readonly  />   
        </el-form-item>
        <el-form-item label="正确答案" >
          <el-input  :value="form.answer" readonly  />
        </el-form-item>
        <el-form-item label="题目解析" >
          <el-input  :value="form.analysis" readonly  />
        </el-form-item>
        <el-form-item label="分数" >
          <el-input  :value="form.score" readonly  />
        </el-form-item>
        <el-form-item label="难度等级" >
          <el-input  :value="proxy.selectDictLabel(exam_question_level, form.level)" readonly   />
        </el-form-item>
        <el-form-item label="课程章节" >
          <el-input  :value="form.section" readonly  />
        </el-form-item>
      </el-form>
    </el-dialog>
    </div>
  </div>
</template>

<script setup name="Question">
import { listQuestion, getQuestion } from "@/api/module/question"
import { getPaperQuestionList,addQuestion,delQuestion,getExam } from "@/api/module/exam"
import { onMounted, reactive } from "vue";
import { useRoute } from 'vue-router'



const { proxy } = getCurrentInstance()
const { exam_question_type, exam_question_level } = proxy.useDict('exam_question_type', 'exam_question_level')

const route = useRoute()
//工作区开关
const workArea = ref(false)
//试卷列表开关
const paperArea = ref(true)
//试卷信息开关
const paperInfoArea=ref(true)

//题库试题列表
const questionList = ref([])
//试卷试题列表
const paperList = ref([])
//左侧题库弹窗开关
const questionOpen = ref(false)
//右侧试卷弹窗开关
const paperQuestionOpen = ref(false)
const loading = ref(true)
//左侧题库搜索开关
const showLeftSearch = ref(true)
//右侧试卷弹窗开关
const showRightSearch = ref(true)
//考试
const exam = ref({
  paperDetail:[0,0,0]
})

//题库添加到试卷数组
const addIds = ref({
  judgeQuestionIds:[],
  multiQuestionIds:[],
  fillQuestionIds:[],
 })
//试卷删除试题数组
const delIds = ref({
  judgeQuestionIds:[],
  multiQuestionIds:[],
  fillQuestionIds:[],
 })

//左侧题库列表总数
const total = ref(0)
//右侧试卷列表总数
const paperTotal = ref(0)
const title = ref("")


//题库数据
const data = reactive({
  form: {
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    questionId: null,
    level: null,
    section: null,
    course: null,
    questionType: null
  },
})

//试题数据
const paperQueryParams=ref({
    pageNum: 1,
    pageSize: 10,
    examCode: route.params.examCode,
    course: null,
    questionType: null,
    level: null,
})

const { queryParams, form } = toRefs(data)


const  changeworkArea=()=>{
  workArea.value=!workArea.value
}
const  changePaperworkArea=()=>{ 
  paperArea.value=!paperArea.value
}

//隐藏试卷开关
const maskPaperInfo=()=>{
  paperInfoArea.value=!paperInfoArea.value
}


/** 查询题库管理列表 */
function getList() {
  loading.value = true
  listQuestion(queryParams.value).then(response => {
    questionList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/**查询试卷列表 */
function getPaperList() {
  loading.value = true
  getPaperQuestionList(paperQueryParams.value).then(response => {
    paperList.value = response.rows
    paperTotal.value = response.total
    loading.value = false
  })
}

/**查询考试详情 */
function getPaperDetail() {
  getExam(route.params.examCode).then(response => {
    exam.value=response.data
  })
}

// 表单重置
function reset() {
  form.value = {
    questionId: null,
    course:queryParams.value.course,
    question: null,
    answer: null,
    analysis: null,
    score: 2,
    level: '1',
    section: null,
    questionType: '1',
    aOption:null,
    bOption:null,
    cOption:null,
    dOption:null,
  }
  proxy.resetForm("questionRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/**试卷搜索按钮操作 */
function handlePaperQuery() {
  queryParams.value.pageNum = 1
  getPaperList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
    queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    questionId: null,
    level: null,
    section: null,
    questionType: null,
    course:route.params.course
  }
  handleQuery()
}

/**试卷重置按钮操作 */
function resetPaperQuery() {
  proxy.resetForm("paperQueryRef")
    paperQueryParams.value = {
    pageNum: 1,
    pageSize: 10,
    examCode: route.params.examCode,
    course: null,
    questionType: null,
    level: null,
    }
    handlePaperQuery();
}



//添加到试卷
function addToPaper(row){
    // 判断是否多选
  if(row.questionType){
    const id=row.questionId
  //清空
  addIds.value = {
    judgeQuestionIds: [],
    multiQuestionIds: [],
    fillQuestionIds: []
  };
  if(row.questionType==1){
      addIds.value.judgeQuestionIds.push(id);
  }else if(row.questionType==2){
      addIds.value.multiQuestionIds.push(id);
  } else if(row.questionType==3){ 
      addIds.value.fillQuestionIds.push(id);
  }
  }
    proxy.$modal.confirm('是否确认添加试题？').then(function() {
      //添加试题
    return addQuestion({
    examCode:route.params.examCode,
    judgeQuestionIds:addIds.value.judgeQuestionIds,
    multiQuestionIds:addIds.value.multiQuestionIds,
    fillQuestionIds:addIds.value.fillQuestionIds,
  })
  }).then(() => {
     //更新试卷试题
     getPaperList()
     //更新试卷详细
      getPaperDetail()
    proxy.$modal.msgSuccess("添加成功")
    getList()
  }).catch(()=>{})
}

// 题库：多选框选中数据方法
function handleSelectionChange(selection) {
  //清空
 addIds.value={
  judgeQuestionIds:[],
  multiQuestionIds:[],
  fillQuestionIds:[],
 }
 //遍历分组
   selection.forEach(item => {
    const id = item.questionId
    const type = item.questionType

    if (type == 1) {
      addIds.value.judgeQuestionIds.push(id)
    } else if (type == 2) {
      addIds.value.multiQuestionIds.push(id)
    } else if (type ==3) {
      addIds.value.fillQuestionIds.push(id)
    }
  })
}

//试卷：多选框选中数据方法
function paperHandleSelectionChange(selection) {
  //清空
 delIds.value={
  judgeQuestionIds:[],
  multiQuestionIds:[],
  fillQuestionIds:[],
 }
 //遍历分组
   selection.forEach(item => {
    const id = item.questionId
    const type = item.questionType

    if (type == 1) {
      delIds.value.judgeQuestionIds.push(id)
    } else if (type == 2) {
      delIds.value.multiQuestionIds.push(id)
    } else if (type ==3) {
      delIds.value.fillQuestionIds.push(id)
    }
  })
}


/** 查看试题详细按钮操作 */
function handleDetial(value,row) {
  reset()
  const _questionId = row?.questionId 
  const _questionType=row?.questionType 
  getQuestion({ questionId: _questionId,questionType:_questionType}).then(response => {
        // 强制补全字段，避免缺失导致异常
    form.value = {
      questionId: null,
      course: route.params.course ?? '',
      question: '',
      answer: '',
      analysis: '',
      score: null,
      level: null,
      section: '',
      questionType: null,
      aOption: null,
      bOption: null,
      cOption: null,
      dOption: null,
      ...response.data // 合并接口数据
    }
    if(value===1){
      questionOpen.value = true
    }else if(value===2){
      paperQuestionOpen.value = true
    }
    title.value = "试题详细"
  })
}


/** 删除试题按钮操作 */
function handleDelete(row) {   
  // 判断是否多选
  if(row.questionType){
    const id=row.questionId
  //清空
  delIds.value = {
    judgeQuestionIds: [],
    multiQuestionIds: [],
    fillQuestionIds: []
  };
  if(row.questionType==1){
      delIds.value.judgeQuestionIds.push(id);
  }else if(row.questionType==2){
      delIds.value.multiQuestionIds.push(id);
  } else if(row.questionType==3){ 
      delIds.value.fillQuestionIds.push(id);
  }
  }

  proxy.$modal.confirm('是否确认删除试题"'  + '"的数据项？').then(function() {
    return delQuestion({
    examCode:route.params.examCode,
    judgeQuestionIds:delIds.value.judgeQuestionIds,
    multiQuestionIds:delIds.value.multiQuestionIds,
    fillQuestionIds:delIds.value.fillQuestionIds,
  })
  }).then(() => {
    getPaperList()
     getPaperDetail()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}




onMounted(() => { 
 getList()
 getPaperList()
 getPaperDetail()
}) 
</script>


<style scoped>
.app-container {
  display: flex;
  gap: 20px;
}

.left-panel,
.right-panel {
  flex: 1;
  padding: 0px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.left-panel h3,
.right-panel h3 {
  margin-bottom: 15px;
}

.info-card {

  padding: 10px 15px;
  border-radius: 4px;
  margin-top: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.label {
  font-weight: bold;

  min-width: 70px;
}

</style>